package com.topInterview;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: huangzhigao
 * @Date: 2022/4/7 16:29
 * 最长无重复子串
 */
public class leecode3_maxLengthSubStr {
    public int lengthOfLongestSubstring(String s) {
        int left = 0;
        int right = 0;
        int res = 0;
        int[] window = new int[256];
        while (right < s.length()) {
            char c = s.charAt(right);
            window[c]++;
            right++;
            while (window[c] > 1) {
                char c1 = s.charAt(left);
                window[c1]--;
                left++;
            }
            res = Math.max(res, right - left);
        }
        return res;
    }


    /***
     * 方法2
     * @param s
     * @return
     */
    public int lengthOfLongestSubstring1(String s) {
        char[] chars = s.toCharArray();
        Map<Character, Integer> map = new HashMap<>();
        int res = 0;
        int start = 0;
        for (int end = 0; end < chars.length; end++) {
            if (map.containsKey(chars[end])) {
                start = Math.max(start, map.get(chars[end]));
            }
            map.put(chars[end], end + 1);
            res = Math.max(res, end - start + 1);
        }
        return res;
    }
}
